#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import importlib.metadata
import os
import sys

import pybamm

# Path for repository root
sys.path.insert(0, os.path.abspath("../"))

# Path for local Sphinx extensions
sys.path.append(os.path.abspath("./sphinxext/"))


# -- Project information -----------------------------------------------------

project = "PyBaMM"
copyright = "2018-2025, The PyBaMM Team"
author = "The PyBaMM Team"

# The short X.Y version
version = importlib.metadata.version("pybamm")
# The full version, including alpha/beta/rc tags
release = version


# -- General configuration ---------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    # Sphinx extensions
    "sphinx.ext.autodoc",
    "sphinx.ext.intersphinx",
    "sphinx.ext.mathjax",
    "sphinx.ext.viewcode",
    "sphinx.ext.napoleon",
    "sphinx.ext.inheritance_diagram",
    # Local and custom extensions
    "extend_parent",
    "inheritance_diagram",
    # Third-party extensions
    "sphinx_design",
    "sphinx_copybutton",
    "myst_parser",
    "sphinx_inline_tabs",
    "sphinxcontrib.bibtex",
    "sphinx_docsearch",
    "sphinx_last_updated_by_git",
    "nbsphinx",  # to be kept below JavaScript-enabled extensions, always
    "IPython.sphinxext.ipython_console_highlighting",
    "sphinx_gallery.load_style",
]


napoleon_use_rtype = True
napoleon_google_docstring = False


# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = ".rst"

# The master toctree document.
master_doc = "index"

# Ignoring links from ScienceDirect
linkcheck_ignore = [
    "https://www.sciencedirect.com",
    "https://doi.org/10.1137/20M1336898",  # DOI link to ignore
    "https://en.wikipedia.org/wiki/",  # Wikipedia link to ignore
    "https://books.google.co.uk/books",
    "https://docs.scipy.org/doc/scipy",  # SciPy docs timeout intermittently
]


# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = "en"

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".ipynb_checkpoints"]

# Suppress warnings generated by Sphinx and/or by Sphinx extensions
suppress_warnings = []

# -- Options for HTML output -------------------------------------------------

html_theme = "pydata_sphinx_theme"

html_static_path = ["_static"]

# Theme

# pydata theme options (see
# https://pydata-sphinx-theme.readthedocs.io/en/latest/index.html# for more information)
# mostly copied from numpy, scipy, pandas
html_logo = "_static/pybamm_logo.png"
html_favicon = "_static/favicon/favicon.png"

html_theme_options = {
    "logo": {
        "image_light": "pybamm_logo.png",
        "image_dark": "pybamm_logo_whitetext.png",
    },
    "icon_links": [
        {
            "name": "GitHub",
            "url": "https://github.com/pybamm-team/pybamm",
            "icon": "fa-brands fa-square-github",
        },
        {
            "name": "Twitter",
            "url": "https://twitter.com/pybamm_",
            "icon": "fa-brands fa-square-twitter",
        },
        {
            "name": "PyPI",
            "url": "https://pypi.org/project/pybamm/",
            "icon": "fa-solid fa-box",
        },
    ],
    "collapse_navigation": True,
    # turn to False to not fail build if json_url is not found
    "check_switcher": True,
    # for dark mode toggle and social media links
    # Note: the version switcher was removed in favour of the readthedocs one
    "navbar_end": ["theme-switcher", "navbar-icon-links"],
    # add Algolia to the persistent navbar, this removes the default search icon
    "navbar_persistent": "algolia-searchbox",
    "navigation_with_keys": False,
    "use_edit_page_button": True,
    "analytics": {
        "plausible_analytics_domain": "docs.pybamm.org",
        "plausible_analytics_url": "https://plausible.io/js/script.js",
    },
    "pygment_light_style": "xcode",
    "pygment_dark_style": "monokai",
    "footer_start": [
        "copyright",
        "sphinx-version",
    ],
    "footer_end": [
        "theme-version",
        "last-updated",
    ],
}

html_title = f"{project} v{version} Manual"
html_last_updated_fmt = "%Y-%m-%d"
html_css_files = ["pybamm.css"]
html_context = {"default_mode": "light"}
html_use_modindex = True
html_copy_source = False
html_domain_indices = False
html_file_suffix = ".html"

htmlhelp_basename = "pybamm"

html_sidebars = {"**": ["sidebar-nav-bs.html", "sidebar-ethical-ads.html"]}

# For edit button
html_context.update(
    {
        "github_user": "pybamm-team",
        "github_repo": "pybamm",
        "github_version": "develop",
        "doc_path": "docs/",
    }
)

# Set canonical URL from the Read the Docs Domain
html_baseurl = os.getenv("READTHEDOCS_CANONICAL_URL", "")

# Tell Jinja2 templates the build is running on Read the Docs
if os.getenv("READTHEDOCS") == "True":
    html_context["READTHEDOCS"] = True

# -- Options for HTMLHelp output ---------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = "PyBaMMdoc"


# -- Options for LaTeX output ------------------------------------------------

# Note: we exclude the examples directory from the LaTeX build because it has
# problems with the creation of PDFs on Read the Docs
# https://github.com/readthedocs/readthedocs.org/issues/2045

# Detect if we are building LaTeX output through the invocation of the build commands
if any("latex" in arg for arg in sys.argv) or any("latexmk" in arg for arg in sys.argv):
    exclude_patterns.append("source/examples/*")
    print("Skipping compilation of .ipynb files for LaTeX build.")

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    #
    # 'papersize': 'letterpaper',
    # The font size ('10pt', '11pt' or '12pt').
    #
    # 'pointsize': '10pt',
    # Additional stuff for the LaTeX preamble.
    #
    # 'preamble': '',
    # Latex figure (float) alignment
    #
    # 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [(master_doc, "PyBaMM.tex", "PyBaMM Documentation", author, "manual")]


# -- Options for manual page output ------------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [(master_doc, "pybamm", "PyBaMM Documentation", [author], 1)]


# -- Options for Texinfo output ----------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (
        master_doc,
        "PyBaMM",
        "PyBaMM Documentation",
        author,
        "PyBaMM",
        "One line description of project.",
        "Miscellaneous",
    )
]


# -- Options for Epub output -------------------------------------------------

# Bibliographic Dublin Core info.
epub_title = project

# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''

# A unique identification for the text.
#
# epub_uid = ''

# A list of files that should not be packed into the epub file.
epub_exclude_files = ["search.html"]


# -- Extension configuration -------------------------------------------------

# -- Options for intersphinx extension ---------------------------------------

# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
    "python": ("https://docs.python.org/3/", None),
    "sphinx": ("https://www.sphinx-doc.org/en/master/", None),
    "numpy": ("https://numpy.org/doc/stable", None),
    "scipy": ("https://docs.scipy.org/doc/scipy", None),
    "matplotlib": ("https://matplotlib.org/stable/", None),
}

# -- sphinxcontrib-bibtex configuration --------------------------------------

bibtex_bibfiles = ["../src/pybamm/CITATIONS.bib"]
bibtex_style = "unsrt"
bibtex_footbibliography_header = """.. rubric:: References"""
bibtex_reference_style = "author_year"
bibtex_tooltips = True

# -- nbsphinx configuration options ------------------------------------------

# Important: ensure require.js is not loaded. this is needed to avoid
# a conflict with the sphinx-docsearch extension for Algolia search

nbsphinx_requirejs_path = ""

# For notebook downloads (23.5 onwards), we get the version from the environment
# variable READTHEDOCS_VERSION and set it accordingly.

# If the version is set to "latest", then we are on the develop branch, and we
# point to the notebook in the develop blob
# If we are on "stable", we point to the notebook in the relevant release tree
# for the PyBaMM version
# On a PR build, we use READTHEDOCS_GIT_COMMIT_HASH which will always point to changes
# made to a notebook, if any.
# On local builds, the version is not set, so we use "latest".

notebooks_version = version
append_to_url = f"blob/v{notebooks_version}"

if (os.environ.get("READTHEDOCS_VERSION") == "latest") or (
    os.environ.get("READTHEDOCS_VERSION") is None
):
    notebooks_version = "develop"
    append_to_url = f"blob/{notebooks_version}"

if os.environ.get("READTHEDOCS_VERSION") == "stable":
    notebooks_version = version
    append_to_url = f"blob/v{notebooks_version}"

if os.environ.get("READTHEDOCS_VERSION_TYPE") == "external":
    notebooks_version = os.environ.get("READTHEDOCS_GIT_COMMIT_HASH")
    append_to_url = f"blob/{notebooks_version}"

github_download_url = f"https://github.com/pybamm-team/PyBaMM/{append_to_url}"
google_colab_url = github_download_url.replace("github.com", "githubtocolab.com")

html_context.update(
    {
        "notebooks_version": notebooks_version,
        "github_download_url": github_download_url,
        "google_colab_url": google_colab_url,
    }
)

nbsphinx_prolog = r"""

{% set github_docname =
'github/pybamm-team/pybamm/blob/develop/docs/' +
env.doc2path(env.docname, base=None) | string() %}

{% set notebooks_version = env.config.html_context.notebooks_version %}
{% set github_download_url = env.config.html_context.github_download_url %}
{% set google_colab_url = env.config.html_context.google_colab_url %}

{% set doc_path = env.doc2path(env.docname, base=None) %}

.. raw:: html

    <div class="admonition tip">
        <p class="admonition-title">
            Tip
        </p>
        <p>
            An interactive online version of this notebook is available, which can be
            accessed via
            <a href="{{ google_colab_url | e }}/docs/{{ doc_path | e }}"
            target="_blank">
            <img src="https://colab.research.google.com/assets/colab-badge.svg"
            alt="Open this notebook in Google Colab"/></a>
        </p>
            <hr>
        <p>
            Alternatively, you may
            <a href="{{ github_download_url | e }}/docs/{{ doc_path | e }}"
            target="_blank" download>
            download this notebook</a> and run it offline.
        </p>
    </div>

"""

if os.environ.get("READTHEDOCS_VERSION") == "latest":
    # append another admonition to warn about unreleased features
    # note: this needs to be appended with a newline and correct dedentation
    nbsphinx_prolog += r"""

    <div class="admonition attention">
        <p class="admonition-title">
            Attention
        </p>
        <p>
            You are viewing this notebook on the latest version of the documentation,
            where these notebooks may not be compatible with the stable release of
            PyBaMM since they can contain features that are not yet released.
            We recommend viewing these notebooks from the stable version of the documentation. To install the latest version of PyBaMM that is compatible with the latest notebooks,
            <a href="https://docs.pybamm.org/en/latest/source/user_guide/installation/index.html\#full-installation-guide
            ">build PyBaMM from source</a>.
        </p>
    </div>

"""

# -- sphinxext/inheritance_diagram.py options --------------------------------

graphviz_output_format = "svg"
inheritance_graph_attrs = dict(
    rankdir="TB",
    size='"10.0, 10.0"',
    fontsize=10,
    ratio="auto",
    center="true",
    nodesep=5,
    ranksep=0.35,
    bgcolor="white",
)
inheritance_node_attrs = dict(
    shape="box",
    fontsize=14,
    fontname="monospace",
    height=0.20,
    color="black",
    style="filled",
)
inheritance_edge_attrs = dict(
    arrowsize=0.75,
    style='"setlinewidth(0.5)"',
)


# -- Options for Algolia DocSearch (sphinx-docsearch) ------------------------

# DocSearch settings
docsearch_app_id = "BXYTEF2JI8"
docsearch_api_key = "b7e7f1fc1a7c40a1587e52e8f4ff3b45"  # search API key, safe to use
docsearch_index_name = "pybamm"

# Searchbox settings
docsearch_container = "#algolia-docsearch"
docsearch_placeholder = "Search the PyBaMM documentation"

# -- Jinja templating --------------------------------------------------------
# Credit to: https://ericholscher.com/blog/2016/jul/25/integrating-jinja-rst-sphinx/


def rstjinja(app, docname, source):
    """
    Render our pages as a jinja template for fancy templating goodness.
    """
    # Make sure we're outputting HTML
    if app.builder.format != "html":
        return
    src = source[0]
    rendered = app.builder.templates.render_string(src, app.config.html_context)
    source[0] = rendered


def setup(app):
    app.connect("source-read", rstjinja)


# Context for Jinja Templates
html_context.update(
    {
        "parameter_sets": pybamm.parameter_sets,
    }
)
